<template>
  <div class="approval-flow-container">
    <el-dialog
      :title="dialogTitle"
      v-model="visible"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      @closed="handleDialogClosed"
      class="approval-flow-dialog"
    >
      <div class="approval-content">
        <!-- 审核流程配置方式选择 - 简化布局 -->
        <div class="config-mode-section">
          <div class="mode-selector-wrapper">
            <el-button-group class="mode-button-group">
              <el-button
                :type="configMode === 'template' ? 'primary' : 'default'"
                size="default"
                @click="handleConfigModeChange('template')"
                class="mode-button"
              >
                <el-icon><List /></el-icon>
                模板审核
              </el-button>
              <el-button
                :type="configMode === 'custom' ? 'primary' : 'default'"
                size="default"
                @click="handleConfigModeChange('custom')"
                class="mode-button"
                :disabled="isTemplateImported"
              >
                <el-icon><Setting /></el-icon>
                自定义审核
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 模板选择模式 -->
        <div v-if="configMode === 'template'" class="template-section">
          <el-card shadow="hover" class="config-card">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span class="card-title">审核模板</span>
                <span></span>
              </div>
            </template>

            <!-- 统一的模板详情预览区域 -->
            <transition name="template-preview-fade" appear>
              <div v-if="shouldShowTemplatePreview" class="unified-template-preview">
                <el-divider content-position="left" class="preview-divider">
                  <span class="preview-title">
                    <el-icon><Document /></el-icon>
                    {{ getTemplatePreviewTitle() }}
                  </span>
                </el-divider>

                <!-- 模板基本信息 -->
                <div class="template-detail-info">
                  <el-descriptions :column="2" border size="default">
                    <el-descriptions-item label="模板名称">
                      {{ getTemplateDisplayData().templateName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="阶段数量"> {{ getTemplateDisplayData().stageCount }} 个审核阶段 </el-descriptions-item>
                    <el-descriptions-item label="模板状态">
                      <el-tag :type="getTemplateStatusType()" size="small">
                        {{ getTemplateStatusText() }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="模板描述">
                      {{ getTemplateDisplayData().description || '暂无描述' }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 审核流程步骤预览 - 仅在选择模板但未导入时显示 -->
                <div v-if="showTemplatePreviewSteps" class="template-flow-preview">
                  <h4 class="flow-title">模板审核流程步骤</h4>
                  <el-steps :active="getTemplateStageList().length" align-center class="preview-steps">
                    <el-step
                      v-for="(stage, index) in getTemplateStageList()"
                      :key="index"
                      :title="stage.stageName || `第${index + 1}阶段`"
                      :description="stage.stageDescription || '暂无描述'"
                      status="finish"
                    />
                  </el-steps>
                </div>

                <!-- 无阶段配置的提示 -->
                <div v-else-if="!hasActualStages && getTemplateStageList().length === 0" class="no-stages-preview">
                  <el-empty description="该模板暂无配置审核阶段" :image-size="80" />
                </div>

                <!-- 已配置的审核流程展示 (仅在 initFlag=1 或 initFlag=2 时显示) -->
                <div v-if="isTemplateImported && configuredTemplate && hasActualStages" class="actual-stages-display">
                  <el-divider content-position="left">
                    <span class="actual-stages-title">
                      <el-icon><List /></el-icon>
                      {{ getConfiguredFlowTitle() }}
                    </span>
                  </el-divider>

                  <!-- 阶段步骤条 -->
                  <div class="actual-stages-steps-section">
                    <el-steps :active="getActiveStageIndex()" align-center class="actual-steps" finish-status="success" process-status="process">
                      <el-step
                        v-for="(stage, index) in configuredTemplate.actualStages"
                        :key="stage.id || index"
                        :title="stage.stageName || `第${index + 1}阶段`"
                        :description="stage.stageDescription || '暂无描述'"
                        :status="getStageStepStatus(stage.approvalStatus)"
                      />
                    </el-steps>
                  </div>

                  <!-- 阶段信息卡片列表 -->
                  <div class="actual-stages-cards">
                    <transition-group name="stage-card" tag="div" class="stage-cards-container">
                      <div
                        v-for="(stage, index) in configuredTemplate.actualStages"
                        :key="stage.id || index"
                        class="actual-stage-card-item"
                        :style="{ '--delay': `${index * 0.1}s` }"
                      >
                        <el-card shadow="hover" class="actual-stage-card">
                          <template #header>
                            <div class="actual-stage-header">
                              <div class="stage-title-section">
                                <span class="stage-title">
                                  <el-icon><Document /></el-icon>
                                  第{{ stage.stageSort || index + 1 }}阶段：{{ stage.stageName || '未命名阶段' }}
                                </span>
                                <div class="stage-tags">
                                  <el-tag :type="getApprovalStatusType(stage.approvalStatus)" size="small">
                                    {{ getApprovalStatusText(stage.approvalStatus) }}
                                  </el-tag>
                                  <el-tag v-if="stage.fixationApprover === '1'" type="warning" size="small" class="fixation-tag">
                                    <el-icon><Lock /></el-icon>
                                    固定审核人员
                                  </el-tag>
                                </div>
                              </div>
                            </div>
                          </template>

                          <div class="actual-stage-content">
                            <!-- 审核人员展示 -->
                            <div class="approvers-display-section">
                              <div class="approvers-panel">
                                <div class="approvers-panel-header">
                                  <span class="approvers-label">
                                    <el-icon><User /></el-icon>
                                    审核人员
                                  </span>
                                  <el-button
                                    type="primary"
                                    link
                                    size="small"
                                    @click="selectActualStageApprovers(index, stage)"
                                    :disabled="!canEditActualStage(stage)"
                                    class="select-approvers-btn"
                                  >
                                    <el-icon><Plus /></el-icon>
                                    {{ stage.approvers && stage.approvers.length > 0 ? '修改人员' : '选择人员' }}
                                  </el-button>
                                </div>

                                <div class="approvers-panel-content">
                                  <template v-if="stage.approvers && stage.approvers.length > 0">
                                    <transition-group name="approver-tag" tag="div" class="approvers-tags-container">
                                      <el-tag
                                        v-for="approver in stage.approvers"
                                        :key="`${stage.id}_${approver.userId}`"
                                        class="approver-tag"
                                        :closable="canEditActualStage(stage)"
                                        @close="removeActualStageApprover(index, approver.userId)"
                                      >
                                        <el-icon><User /></el-icon>
                                        {{ approver.userName || approver.nickName }}
                                      </el-tag>
                                    </transition-group>
                                  </template>
                                  <template v-else>
                                    <div class="no-approvers">
                                      <el-icon><Warning /></el-icon>
                                      <span v-if="stage.fixationApprover === '1'">模板未设置预设审核人员</span>
                                      <span v-else>暂未配置审核人员</span>
                                      <el-button
                                        v-if="stage.fixationApprover !== '1'"
                                        type="primary"
                                        link
                                        size="small"
                                        @click="selectActualStageApprovers(index, stage)"
                                        :disabled="!canEditActualStage(stage)"
                                      >
                                        立即配置
                                      </el-button>
                                    </div>
                                  </template>
                                </div>
                              </div>
                            </div>

                            <!-- 审核意见展示 -->
                            <div v-if="stage.approvalRecords && stage.approvalRecords.length > 0" class="approval-opinions-section">
                              <div class="opinions-header">
                                <span class="opinions-label">
                                  <el-icon><Document /></el-icon>
                                  审核意见：
                                </span>
                              </div>

                              <div class="opinions-list">
                                <transition-group name="opinion-card" tag="div" class="opinions-cards-container">
                                  <div v-for="record in stage.approvalRecords" :key="`${stage.id}_${record.id}`" class="opinion-card">
                                    <div class="opinion-header">
                                      <div class="approver-info">
                                        <el-icon><User /></el-icon>
                                        <span class="approver-name">{{ record.approverName }}</span>
                                        <el-tag :type="getApprovalResultTagType(record.approvalResult)" size="small" class="approval-result-tag">
                                          {{ getApprovalResultText(record.approvalResult) }}
                                        </el-tag>
                                      </div>
                                      <div class="approval-time" v-if="record.approvalTime">
                                        <el-icon><Clock /></el-icon>
                                        <span>{{ formatDateTime(record.approvalTime) }}</span>
                                      </div>
                                    </div>
                                    <div class="opinion-content">
                                      <template v-if="record.approvalOpinion && record.approvalOpinion.trim()">
                                        <div class="opinion-text">{{ record.approvalOpinion }}</div>
                                      </template>
                                      <template v-else>
                                        <div class="no-opinion">暂无审核意见</div>
                                      </template>
                                    </div>
                                  </div>
                                </transition-group>
                              </div>
                            </div>
                          </div>
                        </el-card>
                      </div>
                    </transition-group>
                  </div>
                </div>
              </div>
            </transition>
          </el-card>
        </div>

        <!-- 自定义配置模式 -->
        <div v-if="configMode === 'custom'" class="custom-section">
          <el-card shadow="hover" class="config-card">
            <template #header>
              <div class="custom-card-header">
                <span class="custom-flow-title">自定义审核流程</span>
                <el-button type="primary" @click="addCustomStage" class="add-stage-button-header" size="default" disabled>
                  <el-icon><Plus /></el-icon>
                  添加审核阶段
                </el-button>
              </div>
            </template>

            <!-- 功能暂未开放 -->
            <div class="development-notice">
              <el-empty description="自定义审核流程功能正在开发中" />
            </div>

            <!-- 自定义阶段列表 -->
            <div v-if="customStages.length > 0" class="custom-stages">
              <el-steps :active="customStages.length" align-center class="custom-steps">
                <el-step
                  v-for="(stage, index) in customStages"
                  :key="index"
                  :title="stage.stageName || `第${index + 1}阶段`"
                  :description="stage.stageDescription"
                />
              </el-steps>

              <div class="stage-config-list">
                <div v-for="(stage, index) in customStages" :key="index" class="stage-config-item">
                  <el-card shadow="hover" class="stage-card">
                    <template #header>
                      <div class="stage-header">
                        <span class="stage-title">
                          <el-icon><Document /></el-icon>
                          第{{ index + 1 }}阶段：{{ stage.stageName || '未命名' }}
                        </span>
                        <div class="stage-actions">
                          <el-button size="small" type="primary" link @click="editCustomStage(index)">
                            <el-icon><Edit /></el-icon>
                          </el-button>
                          <el-button size="small" type="danger" link @click="removeCustomStage(index)">
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </div>
                      </div>
                    </template>

                    <div class="stage-content">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <div class="stage-info">
                            <span class="label">审核规则：</span>
                            <el-tag :type="getApprovalRuleType(stage.approvalRule)">
                              {{ getApprovalRuleText(stage.approvalRule) }}
                            </el-tag>
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="stage-info">
                            <span class="label">审核人数：</span>
                            <span>{{ stage.approvers?.length || 0 }}人</span>
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="stage-info">
                            <span class="label">是否必须：</span>
                            <el-tag :type="stage.isRequired === '1' ? 'danger' : 'info'">
                              {{ stage.isRequired === '1' ? '必须' : '非必须' }}
                            </el-tag>
                          </div>
                        </el-col>
                      </el-row>

                      <!-- 审核人员列表 -->
                      <div class="approvers-section mt-3">
                        <span class="label">审核人员：</span>
                        <div class="approvers-list">
                          <el-tag
                            v-for="approver in stage.approvers"
                            :key="approver.userId"
                            class="mr-2 mb-2"
                            closable
                            @close="removeApprover(index, String(approver.userId))"
                          >
                            {{ approver.nickName || approver.userName }}
                          </el-tag>
                          <el-button size="small" type="primary" link @click="selectApprovers(index)">
                            <el-icon><Plus /></el-icon>
                            选择审核人
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-stages">
              <el-empty description="暂无审核阶段，点击上方添加审核阶段按钮开始配置" />
            </div>
          </el-card>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirm" :disabled="!canConfirm" size="large">
            {{ getConfirmButtonText() }}
          </el-button>
          <el-button @click="handleCancel" size="large">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 阶段编辑对话框 -->

    <!-- 用户选择对话框 -->
    <UserSelector
      v-model:visible="userSelectVisible"
      :title="userSelectTitle"
      :selected-user-ids="currentSelectedUserIds"
      :selected-user-names="currentSelectedUserNames"
      :multiple="true"
      @confirm="handleUserSelect"
      @confirmWithIds="handleUserSelectWithIds"
      @cancel="handleUserSelectCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, triggerRef, toRefs, getCurrentInstance } from 'vue';
import {
  Plus,
  Edit,
  Delete,
  Document,
  List,
  Setting,
  Refresh,
  Download,
  User,
  Warning,
  Clock,
  Upload,
  Loading,
  CircleCheck,
  CircleClose,
  RefreshLeft,
  QuestionFilled,
  Lock
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ApprovalStage, ApprovalFlowConfig } from './api/types';
import { initApprovalTemplate, submitApproval, autoImportTemplate } from './api/index';
// 移除对APPROVAL_INIT_STATUS的依赖，现在只用initFlag来判断审核类型
import UserSelector from '@/components/UserSelector/index.vue';

// Props定义
interface Props {
  visible: boolean;
  businessType?: string; // 业务类型，用于区分不同的审核场景
  businessId?: string | number; // 业务ID
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  businessType: '',
  businessId: '',
  title: '配置审核流程'
});

// Emits定义
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'confirm': [data: ApprovalFlowConfig];
  'cancel': [];
  'template-imported': [data: { templateId: string | number; templateName: string; instanceId: number; stages: ApprovalStage[] }];
}>();

// 响应式数据
const dialogTitle = computed(() => props.title);
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const configMode = ref<'template' | 'custom'>('template');
const isTemplateImported = ref(false);
const currentInstanceId = ref<number | null>(null); // 当前审核实例ID
const currentFlowStatus = ref<string>(''); // 当前审核流程状态

// 已配置的模板信息（用于显示模板详情）
const configuredTemplate = ref<{
  templateStages: any[];
  actualStages: any[];
  templateName?: string;
  templateDescription?: string;
  templateStageCount?: number;
  templateIsActive?: string;
  templateCreateTime?: string;
  templateCreateBy?: string;
} | null>(null);

// 自定义阶段相关（暂未开发）
const customStages = ref<ApprovalStage[]>([]);

// 审核人员选择相关
const userSelectVisible = ref(false);
const userSelectTitle = ref('选择审核人员');
const currentSelectStageIndex = ref(-1);
const currentActualStage = ref<any>(null);
// 当前选择的用户ID和姓名字符串（推荐使用的格式）
const currentSelectedUserIds = ref('');
const currentSelectedUserNames = ref('');

// 获取全局实例
const { proxy } = getCurrentInstance() as any;

// 字典数据
const { approval_commit_status, approval_record_status } = toRefs<any>(proxy?.useDict('approval_commit_status', 'approval_record_status'));

// 字典辅助函数
const getDictLabel = (dictRef: any, value: string) => {
  const dictType = dictRef?.value || [];
  const dictItem = dictType.find((item: any) => item.value === value);
  return dictItem ? dictItem.label : '未知';
};

const getDictTagType = (dictRef: any, value: string) => {
  const dictType = dictRef?.value || [];
  const dictItem = dictType.find((item: any) => item.value === value);
  return dictItem?.elTagType || 'info';
};

// 审核人员数据处理辅助函数
const buildApproverData = (approvalRecords: any[]) => {
  if (!approvalRecords || approvalRecords.length === 0) {
    return {
      approvers: [],
      approverIds: '',
      approverNames: ''
    };
  }

  const approvers = approvalRecords.map((record: any) => ({
    userId: record.approverId,
    userName: record.approverName,
    nickName: record.approverName,
    deptName: '', // 如果需要部门信息，可能需要从其他地方获取
    avatar: ''
  }));

  const approverIds = approvalRecords.map((record: any) => record.approverId).join(',');
  const approverNames = approvalRecords.map((record: any) => record.approverName).join(',');

  return {
    approvers,
    approverIds,
    approverNames
  };
};

// 计算属性 - 始终允许提交，由后端判断业务逻辑
const canConfirm = computed(() => {
  // 始终返回 true，让后端来判断是否能提交成功
  return true;
});

// 是否应该显示模板预览
const shouldShowTemplatePreview = computed(() => {
  return isTemplateImported.value && configuredTemplate.value;
});

// 获取模板预览标题
const getTemplatePreviewTitle = () => {
  if (isTemplateImported.value && configuredTemplate.value) {
    return '已配置的审核模板';
  }
  return '模板详情预览';
};

// 获取模板显示数据
const getTemplateDisplayData = () => {
  if (isTemplateImported.value && configuredTemplate.value) {
    return {
      templateName: configuredTemplate.value.templateName || '模板已删除',
      stageCount: configuredTemplate.value.templateStageCount || 0,
      description: configuredTemplate.value.templateDescription || '暂无描述'
    };
  }

  return {
    templateName: '未知模板',
    stageCount: 0,
    description: '暂无描述'
  };
};

// 获取模板状态类型
const getTemplateStatusType = () => {
  if (isTemplateImported.value) {
    return 'success';
  }
  return 'primary';
};

// 获取模板状态文本
const getTemplateStatusText = () => {
  if (isTemplateImported.value) {
    return '已导入';
  }
  return '待导入';
};

// 获取模板阶段列表
const getTemplateStageList = () => {
  if (isTemplateImported.value && configuredTemplate.value?.templateStages) {
    return configuredTemplate.value.templateStages;
  }

  return [];
};

// 新增：是否有实际审核阶段
const hasActualStages = computed(() => {
  return configuredTemplate.value?.actualStages && configuredTemplate.value.actualStages.length > 0;
});

// 新增：是否显示模板预览步骤（由于移除了手动选择，这个计算属性返回false）
const showTemplatePreviewSteps = computed(() => {
  return false; // 不再显示模板预览步骤
});

// 新增：获取已配置流程的标题
const getConfiguredFlowTitle = () => {
  if (!configuredTemplate.value) return '审核流程进度';

  // 根据模板名称判断流程类型
  if (configuredTemplate.value.templateName === '自定义审核流程') {
    return '自定义审核流程进度';
  } else {
    return '审核流程进度';
  }
};

// 注释：移除了 getFlowTypeDescription、getFlowTypeAlertType 和 getConfigurationType 函数，因为不再需要显示流程类型说明和配置状态

// 新增：获取当前激活的阶段索引（用于步骤条显示）
const getActiveStageIndex = () => {
  if (!configuredTemplate.value?.actualStages) return 0;

  // 查找第一个非完成状态的阶段
  const activeIndex = configuredTemplate.value.actualStages.findIndex((stage) => {
    const status = stage.approvalStatus || '0';
    return status !== '3'; // 不是审核通过状态
  });

  // 如果所有阶段都完成了，返回总数；否则返回当前处理的阶段
  return activeIndex === -1 ? configuredTemplate.value.actualStages.length : activeIndex;
};

// 新增：获取阶段状态描述
const getStageStatusDescription = (stage: any) => {
  const status = stage.approvalStatus || '0';
  return getDictLabel(approval_commit_status, status);
};

// 新增：获取步骤条状态
const getStageStepStatus = (approvalStatus: string) => {
  const statusMap: Record<string, 'wait' | 'process' | 'finish' | 'error' | 'success'> = {
    '0': 'wait', // 未提交
    '1': 'process', // 已提交
    '2': 'process', // 审核中
    '3': 'success', // 审核通过
    '4': 'error', // 审核不过
    '5': 'wait', // 已导入
    '6': 'wait' // 已撤销
  };
  return statusMap[approvalStatus] || 'wait';
};

// 方法定义
const getApprovalRuleText = (rule: string) => {
  const map: Record<string, string> = {
    '0': '全员通过',
    '1': '一人通过（暂未开放）',
    '2': '按比例通过（暂未开放）'
  };
  return map[rule] || '未知';
};

const getApprovalRuleType = (rule: string) => {
  const map: Record<string, 'success' | 'warning' | 'primary' | 'info' | 'danger'> = {
    '0': 'success',
    '1': 'info',
    '2': 'info'
  };
  return map[rule] || 'info';
};

const getApprovalStatusText = (status: string) => {
  return getDictLabel(approval_commit_status, status);
};

const getApprovalStatusType = (status: string) => {
  return getDictTagType(approval_commit_status, status);
};

// 获取审核结果文本（使用字典）
const getApprovalResultText = (result: string) => {
  return getDictLabel(approval_record_status, result);
};

// 获取审核结果标签类型（使用字典）
const getApprovalResultTagType = (result: string) => {
  return getDictTagType(approval_record_status, result);
};

// 格式化日期时间
const formatDateTime = (dateTime: string | Date) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return '';

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const handleConfigModeChange = (mode: 'template' | 'custom') => {
  // 清除之前的配置
  customStages.value = [];
  configMode.value = mode;
};

// 移除了模板选择和导入相关的方法，现在由后端自动处理

const addCustomStage = () => {
  // 自定义审核流程功能暂未开发
  return;
};

const editCustomStage = (index: number) => {
  // 自定义审核流程功能暂未开发
  return;
};

const removeCustomStage = (index: number) => {
  customStages.value.splice(index, 1);
  // 重新排序
  customStages.value.forEach((stage, idx) => {
    stage.stageSort = idx + 1;
  });
};

const selectApprovers = (stageIndex: number) => {
  currentSelectStageIndex.value = stageIndex;
  userSelectTitle.value = `选择第${stageIndex + 1}阶段审核人员`;

  // 设置已选中的审核人员
  const currentApprovers = customStages.value[stageIndex].approvers || [];
  currentSelectedUserIds.value = currentApprovers.map((user) => user.userId).join(',');
  currentSelectedUserNames.value = currentApprovers.map((user) => user.userName).join(',');

  userSelectVisible.value = true;
};

const removeApprover = (stageIndex: number, userId: string) => {
  const stage = customStages.value[stageIndex];
  if (stage.approvers) {
    stage.approvers = stage.approvers.filter((approver: any) => approver.userId !== userId);
  }
};

const handleConfirm = async () => {
  try {
    if (configMode.value === 'template') {
      // 提交审核配置，由后端判断是否可以提交
      await submitApprovalConfigData();
    } else {
      // 自定义模式暂未开发，也尝试提交让后端返回相应错误
      await submitApprovalConfigData();
    }
  } catch (error) {
    console.error('提交审核失败:', error);
  }
};

const handleCancel = () => {
  emit('cancel');
  visible.value = false;
};

const handleDialogClosed = () => {
  // 重置所有数据，确保始终回到模板模式
  configMode.value = 'template';
  customStages.value = [];
  // 重置导入状态
  isTemplateImported.value = false;
  configuredTemplate.value = null;
  currentInstanceId.value = null;
  currentFlowStatus.value = '';
  // 重置用户选择状态
  userSelectVisible.value = false;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
};

// 监听visible变化，初始化审核信息
watch(visible, (newVal) => {
  if (newVal) {
    // 初始化审核信息（检查是否已配置，如果没有配置会自动导入模板）
    initApprovalInfo();
  }
});

// 注释：移除了 loadImportedStages 函数，现在统一使用 initApprovalInfo 来获取完整的审核信息

/**
 * 初始化审核信息 - 检查是否已配置过审核流程并获取完整数据
 * @param silent 静默模式，不显示成功提示
 */
const initApprovalInfo = async (silent = false) => {
  // 检查必要参数
  if (!props.businessType || !props.businessId) {
    return;
  }

  try {
    const params = {
      businessType: props.businessType,
      businessId: props.businessId
    };
    const response = await initApprovalTemplate(params);

    if (response && response.code === 200) {
      const responseData = response.data;

      // 检查是否可以自动导入模板
      if (responseData.autoImportAvailable && responseData.availableTemplateId) {
        // 调用自动导入接口
        const autoImportParams = {
          businessType: props.businessType,
          businessId: Number(props.businessId),
          templateId: responseData.availableTemplateId
        };

        try {
          const autoImportResponse = await autoImportTemplate(autoImportParams);

          if (autoImportResponse && autoImportResponse.code === 200) {
            // 自动导入成功，直接使用返回的数据
            handleInitSuccess(autoImportResponse.data, silent);
          } else {
            console.error('自动导入模板失败:', autoImportResponse?.msg || '未知错误');
            // 即使自动导入失败，也使用原始响应数据
            handleInitSuccess(responseData, silent);
          }
        } catch (autoImportError) {
          console.error('自动导入模板异常:', autoImportError);
          // 即使自动导入失败，也使用原始响应数据
          handleInitSuccess(responseData, silent);
        }
      } else {
        // 正常处理初始化数据
        handleInitSuccess(responseData, silent);
      }
    } else {
      console.error('初始化模板失败:', response?.msg || '未知错误');
    }
  } catch (error) {
    console.error('初始化模板异常:', error);
  }
};

/**
 * 处理初始化成功的通用逻辑
 */
const handleInitSuccess = (data: any, silent: boolean) => {
  const { initFlag, stageList, flowTemplate, instanceId, flowStatus } = data;

  // 保存实例ID和流程状态
  if (instanceId) {
    currentInstanceId.value = instanceId;
  }

  // 设置流程状态（从后端返回的数据中获取）
  currentFlowStatus.value = flowStatus || '0';

  // 根据initFlag判断审核类型
  if (initFlag === '0') {
    // 没有设置审核流程
    isTemplateImported.value = false;
    configuredTemplate.value = null;
    currentInstanceId.value = null;
    currentFlowStatus.value = '0';
  } else if (initFlag === '1') {
    // 模板审核流程
    isTemplateImported.value = true;

    if (stageList && stageList.length > 0) {
      // 设置模板配置信息，包含模板基础信息和实际阶段
      configuredTemplate.value = {
        templateStages: flowTemplate?.stageList || [],
        actualStages: stageList.map((stage: any) => {
          const approverData = buildApproverData(stage.approvalRecords);
          return {
            id: stage.id,
            stageName: stage.stageName,
            stageSort: stage.stageSort,
            stageDescription: stage.stageDescription,
            businessType: stage.businessType,
            businessId: stage.businessId,
            approvalStatus: stage.approvalStatus || '0',
            approvalRecords: stage.approvalRecords || [],
            fixationApprover: stage.fixationApprover || '0', // 保留固定审核人员标识
            ...approverData
          };
        }),
        templateName: flowTemplate?.templateName || '模板已删除',
        templateDescription: flowTemplate?.description || '暂无',
        templateStageCount: flowTemplate?.stageCount || stageList.length,
        templateIsActive: flowTemplate?.isActive || '0',
        templateCreateTime: flowTemplate?.createTime || '',
        templateCreateBy: flowTemplate?.createBy || ''
      };

      // 已有审核模板配置
    } else {
      // 找到审核模板配置但缺少阶段信息
    }
  } else if (initFlag === '2') {
    // 自定义审核流程（暂未开发）
    isTemplateImported.value = true;

    if (stageList && stageList.length > 0) {
      // 设置自定义流程信息
      configuredTemplate.value = {
        templateStages: [],
        actualStages: stageList.map((stage: any) => {
          const approverData = buildApproverData(stage.approvalRecords);
          return {
            id: stage.id,
            stageName: stage.stageName,
            stageSort: stage.stageSort,
            stageDescription: stage.stageDescription,
            businessType: stage.businessType,
            businessId: stage.businessId,
            approvalStatus: stage.approvalStatus || '0',
            approvalRecords: stage.approvalRecords || [],
            fixationApprover: stage.fixationApprover || '0', // 保留固定审核人员标识
            ...approverData
          };
        }),
        templateName: '自定义审核流程',
        templateDescription: '用户自定义创建的审核流程',
        templateStageCount: stageList.length,
        templateIsActive: '1'
      };

      // 检测到已有自定义审核配置
    } else {
      // 找到自定义审核配置但缺少阶段信息
    }
  } else {
    // 检测到未知的审核配置状态
    isTemplateImported.value = false;
    configuredTemplate.value = null;
  }
};

// 移除了 loadTemplateList 函数，因为不再需要手动加载模板列表

onMounted(() => {
  // 如果组件挂载时就是可见状态，则需要立即初始化（静默模式）
  if (visible.value) {
    initApprovalInfo(true);
  }
});

// 获取确认按钮文字
const getConfirmButtonText = () => {
  return '提交审核';
};

// 新的用户选择处理函数：使用统一的数据格式
const handleUserSelectWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  // 根据不同的选择场景处理数据
  if (currentSelectStageIndex.value !== -1 && currentSelectStageIndex.value !== -3) {
    // 为自定义阶段设置审核人员
    if (customStages.value[currentSelectStageIndex.value]) {
      customStages.value[currentSelectStageIndex.value].approvers = [...data.users];
    }
  } else if (currentActualStage.value) {
    // 为实际阶段设置审核人员
    currentActualStage.value.approvers = [...data.users];
    currentActualStage.value.approverIds = data.userIds;
    currentActualStage.value.approverNames = data.userNames;

    // 同时更新configuredTemplate中对应的阶段数据
    if (configuredTemplate.value?.actualStages) {
      const stageIndex = configuredTemplate.value.actualStages.findIndex((stage) => stage.id === currentActualStage.value.id);

      if (stageIndex !== -1) {
        configuredTemplate.value.actualStages[stageIndex].approvers = [...data.users];
        configuredTemplate.value.actualStages[stageIndex].approverIds = data.userIds;
        configuredTemplate.value.actualStages[stageIndex].approverNames = data.userNames;

        // 强制触发响应式更新
        nextTick(() => {
          triggerRef(configuredTemplate);
        });
      }
    }

    // 调用API更新后端数据
    updateActualStageApproversWithIds(currentActualStage.value.id, data.userIds, data.userNames);
  }

  // 清理临时数据
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
};

// 处理用户选择确认（保留向后兼容）
const handleUserSelect = (users: any[]) => {
  if (currentSelectStageIndex.value !== -1 && currentSelectStageIndex.value !== -3) {
    // 为自定义阶段设置审核人员
    if (customStages.value[currentSelectStageIndex.value]) {
      customStages.value[currentSelectStageIndex.value].approvers = [...users];
    }
  } else if (currentActualStage.value) {
    // 为实际阶段设置审核人员
    currentActualStage.value.approvers = [...users];

    // 同时更新configuredTemplate中对应的阶段数据
    if (configuredTemplate.value?.actualStages) {
      const stageIndex = configuredTemplate.value.actualStages.findIndex((stage) => stage.id === currentActualStage.value.id);

      if (stageIndex !== -1) {
        configuredTemplate.value.actualStages[stageIndex].approvers = [...users];

        // 强制触发响应式更新
        nextTick(() => {
          triggerRef(configuredTemplate);
        });
      }
    }

    // 调用API更新后端数据
    updateActualStageApprovers(currentActualStage.value.id, users, true);
  }

  // 清理临时数据
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
};

// 处理用户选择取消
const handleUserSelectCancel = () => {
  // 清理临时数据
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
};

// 选择实际阶段的审核人员
const selectActualStageApprovers = (stageIndex: number, stage: any) => {
  // 如果是固定审核人员，不允许选择
  if (stage.fixationApprover === '1') {
    ElMessage.warning('该阶段审核人员已由模板固定，无法修改');
    return;
  }

  currentActualStage.value = stage;
  currentSelectStageIndex.value = -3; // 使用特殊值标识实际阶段
  userSelectTitle.value = `选择第${stage.stageSort || stageIndex + 1}阶段审核人员`;

  // 直接使用字符串格式数据，UserSelector会自动处理
  currentSelectedUserIds.value = stage.approverIds || '';
  currentSelectedUserNames.value = stage.approverNames || '';

  userSelectVisible.value = true;
};

// 移除实际阶段的审核人员
const removeActualStageApprover = (stageIndex: number, userId: string | number) => {
  if (configuredTemplate.value?.actualStages && configuredTemplate.value.actualStages[stageIndex]) {
    const stage = configuredTemplate.value.actualStages[stageIndex];

    // 如果是固定审核人员，不允许移除
    if (stage.fixationApprover === '1') {
      ElMessage.warning('该阶段审核人员已由模板固定，无法修改');
      return;
    }

    if (stage.approvers) {
      // 从列表中移除
      stage.approvers = stage.approvers.filter((approver: any) => approver.userId !== userId);

      // 调用API更新后端数据
      updateActualStageApprovers(stage.id, stage.approvers);
    }
  }
};

// 判断实际阶段是否可以编辑 - 考虑固定审核人员设置
const canEditActualStage = (stage: any) => {
  // 如果是固定审核人员，不允许编辑
  if (stage.fixationApprover === '1') {
    return false;
  }
  // 其他情况返回 true，让后端来判断具体的业务逻辑
  return true;
};

// 更新实际阶段的审核人员（使用新的字符串格式）
const updateActualStageApproversWithIds = async (stageId: string | number, userIds: string, userNames: string) => {
  try {
    // 这里应该调用后端API更新审核人员，直接使用字符串格式
    // await updateApprovalStageApproversByIds(stageId, userIds, userNames)
  } catch (error) {
    console.error('更新审核人员失败:', error);
    ElMessage.error('更新审核人员失败');
  }
};

// 更新实际阶段的审核人员（调用后端API）
const updateActualStageApprovers = async (stageId: string | number, approvers: any[], showMessage: boolean = false) => {
  try {
    // 这里应该调用后端API更新审核人员
    // await updateApprovalStageApprovers(stageId, approvers)
  } catch (error) {
    console.error('更新审核人员失败:', error);
    ElMessage.error('更新审核人员失败');
  }
};

// 提交审核配置
const submitApprovalConfigData = async () => {
  try {
    // 构建提交数据，如果没有配置阶段则发送空数组，让后端判断
    const formattedStages = configuredTemplate.value?.actualStages
      ? configuredTemplate.value.actualStages.map((stage) => ({
          id: stage.id,
          stageName: stage.stageName,
          stageSort: stage.stageSort,
          businessType: stage.businessType,
          approvalStatus: stage.approvalStatus,
          fixationApprover: stage.fixationApprover || '0',
          approvers: stage.approvers?.map((approver) => approver.userId).join(',') || ''
        }))
      : [];

    // 调用后端API提交审核，让后端来判断所有业务逻辑
    const response = await submitApproval({
      instanceId: currentInstanceId.value,
      businessType: props.businessType,
      businessId: Number(props.businessId),
      submitType: 'template',
      stages: formattedStages
    });

    // 关闭对话框
    visible.value = false;

    // 触发成功事件
    emit('confirm', {
      type: 'template' as const,
      stages: formattedStages
    });
  } catch (error) {
    console.error('提交审核失败:', error);
    // 错误处理由后端返回的错误信息来显示，这里不做额外处理
  }
};
</script>
<style scoped>
/* 整体容器样式 */
.approval-flow-container {
  padding: 0;
}

.approval-content {
  max-height: 65vh;
  overflow-y: auto;
  padding: 10px 0;
}

/* 审核模式选择区域 - 左上角布局 */
.config-mode-section {
  margin-bottom: 32px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.mode-selector-wrapper {
  display: flex;
  justify-content: flex-start;
}

.mode-button-group {
  border-radius: 8px;
  overflow: hidden;
}

.mode-button {
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 0;
  transition: all 0.3s ease;
}

.mode-button:first-child {
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
}

.mode-button:last-child {
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}

/* 自定义模式按钮样式 */
.mode-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 配置卡片样式 */
.template-section,
.custom-section {
  margin-bottom: 20px;
}

.config-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
}

/* 自定义审核流程标题与按钮间距 */
.custom-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-flow-title {
  font-weight: 700;
  font-size: 18px;
}

/* 添加阶段按钮区域 */
.add-stage-section {
  text-align: center;
  margin-top: 50px;
  padding: 40px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.add-stage-button {
  padding: 16px 32px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

/* 模板选择器选项样式 */
.template-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.template-option-name {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.template-option-desc {
  font-size: 12px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
}

.template-option-stages {
  font-size: 12px;
  color: var(--el-color-primary);
  font-weight: 500;
}

/* 统一模板预览样式 */
.unified-template-preview {
  margin-top: 24px;
}

.preview-divider {
  margin: 20px 0 16px 0;
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: var(--el-color-primary);
}

.preview-title .el-icon {
  color: var(--el-color-primary);
  font-size: 18px;
}

/* 模板预览淡入动画 */
.template-preview-fade-enter-active {
  transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}

.template-preview-fade-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.98);
}

.template-preview-fade-leave-active {
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

.template-preview-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(1.02);
}

.template-detail-info {
  margin-bottom: 24px;
}

.template-flow-preview {
  margin-top: 20px;
}

.flow-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.preview-steps {
  margin-bottom: 24px;
}

.no-stages-preview {
  text-align: center;
  padding: 40px 20px;
}

/* 已配置模板显示样式 */
.configured-template-section {
  margin-top: 32px;
}

.configured-divider {
  margin: 24px 0 20px 0;
}

.configured-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: var(--el-color-success);
}

.configured-template-info {
  margin-bottom: 24px;
}

.configured-flow-preview {
  margin-top: 20px;
  margin-bottom: 24px;
}

.configured-flow-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.configured-steps {
  margin-bottom: 24px;
}

.actual-stages-section {
  margin-top: 24px;
}

.actual-stages-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.actual-stages-list {
  margin-top: 20px;
}

.stage-cards-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.actual-stage-card {
  opacity: 0;
  transform: translateY(20px);
  animation: slideInUp 0.6s ease-out forwards;
  animation-delay: var(--delay);
}

.stage-card-actual {
  border-radius: 12px;
  overflow: hidden;
  border: 2px solid var(--el-color-success-light-7);
  transition: all 0.3s ease;
}

.stage-card-actual:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(103, 194, 58, 0.15);
  border-color: var(--el-color-success-light-5);
}

.stage-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stage-card-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.stage-card-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: var(--el-color-success);
}

.stage-card-content {
  padding-top: 16px;
}

.stage-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.info-label {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-regular);
  min-width: 80px;
  flex-shrink: 0;
}

/* 模板配置淡入动画 */
.template-config-fade-enter-active {
  transition: all 0.8s ease-out;
}

.template-config-fade-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.approvers-config-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 已导入模板额外信息样式 */
.imported-template-extra-info {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-light);
}

.extra-info-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--el-color-success);
}

.extra-info-title .el-icon {
  color: var(--el-color-success);
  font-size: 16px;
}

.approvers-placeholder {
  flex: 1;
  padding: 8px 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
  border: 1px dashed var(--el-border-color);
}

/* 动画定义 */
@keyframes slideInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 整体淡入动画 */
.stage-cards-fade-enter-active {
  transition: all 0.8s ease-out;
}

.stage-cards-fade-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

/* 卡片进入动画 */
.stage-card-enter-active {
  transition: all 0.6s ease-out;
}

.stage-card-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.stage-card-leave-active {
  transition: all 0.4s ease-in;
}

.stage-card-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

/* 自定义阶段样式 */
.custom-stages {
  margin-top: 24px;
}

.custom-steps {
  margin-bottom: 32px;
}

.stage-config-list {
  margin-top: 24px;
}

.stage-config-item {
  margin-bottom: 20px;
}

.stage-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stage-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.stage-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.stage-actions {
  display: flex;
  gap: 8px;
}

.stage-content {
  padding-top: 16px;
}

.stage-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  font-weight: 600;
  margin-right: 8px;
  min-width: 80px;
}

.approvers-section {
  padding-top: 16px;
  margin-top: 16px;
}

.approvers-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}

.empty-stages {
  text-align: center;
  padding: 60px 20px;
}

.dialog-footer {
  text-align: right;
  padding: 24px 0 8px 0;
}

.ratio-tip {
  margin-left: 12px;
  font-size: 13px;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 12px;
}

/* 步骤条样式 */
:deep(.el-steps) {
  margin-bottom: 24px;
}

/* 单选框组样式 */
:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 水平单选框组样式 */
.horizontal-radio-group :deep(.el-radio) {
  margin-right: 24px;
  margin-bottom: 0;
}

.horizontal-radio-group {
  display: flex !important;
  flex-direction: row !important;
  gap: 0 !important;
  align-items: center;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
}

/* 按钮样式 */
:deep(.el-button--primary) {
  border-radius: 6px;
}

/* 选择框样式 */
:deep(.el-select) {
  width: 100%;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 模板选项样式 */
.template-option {
  display: flex;
  justify-content: space-between;
}

.template-description {
  font-size: 13px;
}

/* 按钮组样式 */
:deep(.el-button-group) {
  border-radius: 8px;
  overflow: hidden;
}

/* 自定义卡片header样式 */
.custom-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-flow-title {
  font-weight: 700;
  font-size: 18px;
}

.add-stage-button-header {
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

/* 比例提示样式 */
.ratio-tip {
  margin-left: 12px;
  font-size: 13px;
}

.approvers-section {
  width: 100%;
}

.selected-approvers {
  margin-bottom: 12px;
  min-height: 32px;
}

.approver-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 6px;
  font-weight: 500;
}

.select-approver-btn {
  border-radius: 8px;
  font-weight: 600;
}

.approver-tip {
  margin-top: 8px;
}

/* 功能开发中提示样式 */
.development-notice {
  margin: 24px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .approval-content {
    padding: 8px;
  }

  .config-card :deep(.el-card__body) {
    padding: 16px;
  }

  .stage-edit-form {
    padding: 16px;
  }

  .add-stage-section {
    padding: 24px;
  }

  .add-stage-button {
    padding: 12px 20px;
    font-size: 14px;
  }

  .custom-card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .add-stage-button-header {
    width: 100%;
  }

  /* 模板预览响应式 */
  .template-detail-info :deep(.el-descriptions) {
    font-size: 13px;
  }

  .flow-title {
    font-size: 15px;
  }

  .preview-steps :deep(.el-step__title) {
    font-size: 12px;
    line-height: 1.3;
  }

  .preview-steps :deep(.el-step__description) {
    font-size: 11px;
  }

  /* 导入按钮响应式 */
  .template-select-area {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .import-template-btn,
  .revoke-template-btn {
    width: 100%;
  }

  /* 导入卡片响应式 */
  .stage-info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .info-label {
    min-width: auto;
    margin-bottom: 4px;
  }

  .stage-description-imported,
  .approvers-config-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  /* 实际阶段响应式 */
  .actual-stage-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .stage-title-section {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .actual-stage-actions {
    justify-content: center;
  }

  /* 审核人员面板响应式 */
  .approvers-panel-header {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }

  .select-approvers-btn {
    width: 100%;
    justify-content: center;
  }

  .approvers-panel-content {
    padding: 12px;
  }

  /* 审核意见响应式 */
  .opinion-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .approver-info {
    flex-wrap: wrap;
    gap: 6px;
  }

  .approval-time {
    font-size: 11px;
  }

  .opinion-card {
    padding: 12px;
  }

  .opinion-content {
    padding: 10px;
  }

  .opinion-text {
    font-size: 13px;
    line-height: 1.5;
  }
}

/* 新增：实际审核阶段相关样式 */
.actual-stages-display {
  margin-top: 24px;
}

.actual-stages-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: var(--el-color-primary);
}

.actual-stages-title .el-icon {
  color: var(--el-color-primary);
  font-size: 18px;
}

.actual-stages-steps-section {
  margin-bottom: 24px;
}

.actual-steps {
  margin-bottom: 24px;
}

.actual-stages-cards {
  margin-bottom: 24px;
}

.stage-cards-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.actual-stage-card-item {
  opacity: 0;
  transform: translateY(20px);
  animation: slideInUp 0.6s ease-out forwards;
  animation-delay: var(--delay);
}

.actual-stage-card {
  border-radius: 12px;
  overflow: hidden;
  border: 2px solid var(--el-color-primary-light-7);
  transition: all 0.3s ease;
}

.actual-stage-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);
  border-color: var(--el-color-primary-light-5);
}

.actual-stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.stage-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.stage-tags {
  display: flex;
  align-items: center;
  gap: 8px;
}

.fixation-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
}

.stage-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.stage-title .el-icon {
  color: var(--el-color-primary);
  font-size: 18px;
}

.stage-status-tag {
  font-weight: 500;
}

.actual-stage-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.actual-stage-content {
  padding-top: 20px;
}

.stage-info-row {
  margin-bottom: 20px;
}

.stage-info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.info-label {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-regular);
  min-width: 80px;
  flex-shrink: 0;
}

.info-value {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.approvers-display-section {
  margin-top: 16px;
  padding-top: 0;
}

.approvers-panel {
  background-color: var(--el-fill-color-extra-light);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  overflow: hidden;
}

.approvers-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-color-primary-light-9);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.approvers-panel-content {
  padding: 16px;
  min-height: 48px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.select-approvers-btn {
  font-weight: 500;
  transition: all 0.3s ease;
}

.select-approvers-btn:hover:not(:disabled) {
  transform: scale(1.05);
}

.approvers-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.approvers-label .el-icon {
  color: var(--el-color-primary);
  font-size: 16px;
}

.approvers-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  width: 100%;
  min-height: 20px;
}

.approver-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  background-color: var(--el-color-primary-light-8);
  border-color: var(--el-color-primary-light-6);
}

.approver-tag .el-icon {
  font-size: 12px;
}

.approver-tag:hover {
  transform: scale(1.02);
}

/* 新增审核人员的动画效果 */
.approver-tag-enter-active {
  transition: all 0.6s ease;
}

.approver-tag-enter-from {
  opacity: 0;
  transform: translateX(-20px) scale(0.8);
}

.approver-tag-leave-active {
  transition: all 0.4s ease;
}

.approver-tag-leave-to {
  opacity: 0;
  transform: translateX(20px) scale(0.8);
}

/* 审核人员更新时的闪烁效果 */
@keyframes approver-highlight {
  0% {
    background-color: var(--el-color-primary-light-9);
  }
  50% {
    background-color: var(--el-color-primary-light-7);
  }
  100% {
    background-color: transparent;
  }
}

.approver-tag.updated {
  animation: approver-highlight 1s ease-in-out;
}

.no-approvers {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  width: 100%;
  color: var(--el-text-color-regular);
  font-size: 14px;
  text-align: center;
  flex-wrap: wrap;
  min-height: 20px;
}

.no-approvers > span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.no-approvers .el-icon {
  color: var(--el-color-warning);
  font-size: 16px;
}

.stage-description {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.description-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.description-header .el-icon {
  color: var(--el-color-primary);
  font-size: 16px;
}

.description-content {
  padding: 12px 16px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}

/* 审核意见展示区域样式 */
.approval-opinions-section {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.opinions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.opinions-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.opinions-label .el-icon {
  color: var(--el-color-primary);
  font-size: 16px;
}

.opinions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.opinions-cards-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.opinion-card {
  background-color: var(--el-fill-color-extra-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.opinion-card:hover {
  border-color: var(--el-color-primary-light-5);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.opinion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.approver-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.approver-name {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.approval-result-tag {
  font-weight: 500;
  border-radius: 4px;
}

.approval-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.approval-time .el-icon {
  font-size: 12px;
}

.opinion-content {
  background-color: var(--el-bg-color);
  border-radius: 6px;
  padding: 12px;
  border-left: 3px solid var(--el-color-primary);
}

.opinion-text {
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
  word-break: break-word;
}

.no-opinion {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

/* 审核意见卡片动画 */
.opinion-card-enter-active {
  transition: all 0.6s ease;
}

.opinion-card-enter-from {
  opacity: 0;
  transform: translateY(10px) scale(0.98);
}

.opinion-card-leave-active {
  transition: all 0.4s ease;
}

.opinion-card-leave-to {
  opacity: 0;
  transform: translateY(-5px) scale(0.98);
}

/* 卡片过渡动画 */
.stage-card-enter-active,
.stage-card-leave-active {
  transition: all 0.6s ease;
}

.stage-card-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.stage-card-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.stage-card-move {
  transition: transform 0.6s ease;
}
</style>
